package com.nuonuo.es.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;

@Configuration
public class ElasticSearchConfig {

    @Value("${elasticsearch.hosts}")
    private String hosts;

    @Value("${elasticsearch.clusterName}")
    private String clusterName;

    @Bean
    public TransportClient getTransportClient(){
        System.setProperty("es.set.netty.runtime.available.processors", "false");
        try{
            Settings settings = Settings.builder().
                    put("client.transport.sniff", true)
                    .put("cluster.name",clusterName).
                            build();

            TransportClient client = new PreBuiltTransportClient(settings);
            //分号
            String[] addressArray = hosts.split(";");

            if(addressArray==null){
                throw new Exception("ES服務配置异常");
            }
            for(String address: addressArray){
                //冒号
                String[] addressParts = address.split(":");
                String host = address;
                int port = 9300;
                if(addressParts.length==2){
                    host = addressParts[0];
                    port = Integer.parseInt(addressParts[1]);
                }

                client.addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));
            }

            return  client;
        }catch(Exception e){
           e.printStackTrace();
            System.exit(1);
            return null;
        }
    }
}
